package library.server;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.sql.DataSource;

public class MySQLConnection {
	private Connection connection;
	private Statement statement;
	
	public MySQLConnection(DataSource ds) throws SQLException {
		connection = ds.getConnection();
		statement = connection.createStatement();
	}

	public MySQLConnection(String user, String password) throws SQLException {
		// carico il driver di MySQL
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// setup the connection with the DB.
		connection = DriverManager
				.getConnection("jdbc:mysql://localhost/LibraryDB?" + "user="
						+ user + "&password=" + password);
		statement = connection.createStatement();
		// statements allow to issue SQL queries to the database
	}

	public ResultSet executeQuery(String query) throws SQLException {
		if (statement != null) {
			return statement.executeQuery(query);
		} else {
			return null;
		}

	}

	public PreparedStatement createPreparedStatement(String parametrizedQuery)
			throws SQLException {
		if (connection != null)
			return connection.prepareStatement(parametrizedQuery);
		else
			return null;
	}

	public void closeConnection() {
		try {
			if (statement != null) {
				statement.close();
				statement = null;
			}
			if (connection != null) {
				connection.close();
				connection = null;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	@Override
	protected void finalize() {
		try {
			closeConnection();
		} finally {
			try {
				super.finalize();
			} catch (Throwable e) {
				e.printStackTrace();
			}
		}
	}

}
